package com.itbaizhan.ajax.servlet;

import com.alibaba.fastjson.JSON;
import com.itbaizhan.ajax.pojo.User;
import org.apache.commons.lang.StringUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/*用户管理servlet*/
@WebServlet("/user.do")
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //找到前端页面index.jsp 中的初始数据方法，进行调用
        //在doData方法中的参数flag
        String flag = req.getParameter("flag");
        if(flag.equals("getData")){
            //把下面的ServletContext 中的list 放进前端
            //调用方法
            this.getData(req,resp);
        }else if (flag.equals("addUser")){
            this.addUser(req,resp);
        }else if (flag.equals("updateUser")){
            this.updateUser(req,resp);
        }else if(flag.equals("delete")){
            this.deleteUser(req,resp);
        }
    }


    //删除用户  用全局性contextServlet取到list集合中的数据，然后用list转为map 找出对应的id的user 再进行删除
    private void deleteUser(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        ServletContext servletContext = this.getServletContext();
        List<User> list =(List<User>) servletContext.getAttribute("list");
        //取到前端传来的id  利用传来的参数userid
        String userid = req.getParameter("userid");
        //list转为map
        Map<String,User> userMap =list.stream().collect(Collectors.toMap(User::getId,Function.identity()));
        if (StringUtils.isNotEmpty(userid)){
            //取到要删除的user
            User user = userMap.get(userid);
            list.remove(user);
            //在前端输出
            resp.setContentType("text/plain;charset=utf-8");
            PrintWriter pw = resp.getWriter();
            pw.println("删除成功");
            pw.flush();
            pw.close();
        }else {
            resp.setContentType("text/plain;charset=utf-8");
            PrintWriter pw = resp.getWriter();
            pw.println("删除失败");
            pw.flush();
            pw.close();
        }
    }


    //更新用户，  因为id是唯一的（这里省略了id的校检）， 先取到旧的数据， 将旧的删除，添加新的进去
    private void updateUser(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //获取更新后的数据
        User user = this.createUser(req);
        //利用servletContext的全局性获得之前的list
        ServletContext servletContext = this.getServletContext();
        List<User> list =(List<User>) servletContext.getAttribute("list");
        //根据id将旧的删除   可以遍历list，找到对应的id  也可以用map   把list转为map
        //Function.identity() 返回的是输入与输出一样的对象
        Map<String,User> userMap=list.stream().collect(Collectors.toMap(User::getId, Function.identity()));
        //根据id获得旧的user   更新后的数据的id与之前的id一样
        User user1 = userMap.get(user.getId());
        list.remove(user1);
        //添加新的对象
        list.add(user);
        //按id重新排序
        list.sort(new Comparator<User>() {
            @Override
            public int compare(User o1, User o2) {
                return Integer.parseInt(o1.getId()) - Integer.parseInt(o2.getId());
            }
        });
        //输出页面
        resp.setContentType("text/plain;charset=utf-8");
        PrintWriter pw = resp.getWriter();
        pw.println("更新成功");
        pw.flush();
        pw.close();
    }

    //添加用户数据，更新用户数据
    private void addUser(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //调用下面的createUser()  得到新添加的user
        User user = this.createUser(req);
        //利用全局性对象，获取所有数据
        ServletContext servletContext = this.getServletContext();
        List<User> list = (List<User>) servletContext.getAttribute("list");
        list.add(user);
        resp.setContentType("text/plain;charset=utf-8");
        PrintWriter pw = resp.getWriter();
        pw.println("添加成功");
        pw.flush();
        pw.close();

    }
    //返回一个用户对象
    private User createUser(HttpServletRequest request){
        //获取数据
        String userid = request.getParameter("userid");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String salary = request.getParameter("salary");
        String birthday = request.getParameter("birthday");
        //放进user对象
        User user = new User();
        user.setId(userid);
        user.setPassword(password);
        user.setUsername(username);
        user.setBirthday(birthday);
        user.setSalary(Double.parseDouble(salary));//强转类型
        return user;


    }

    @Override
    public void init() throws ServletException {
        //初始化数据
        ArrayList<User> list = new ArrayList<>();
        //在User类中有带参的构造器
        User user1 = new User("1","zhan","112","1990-02-12",8000d);
        User user2 = new User("2","li","113","1992-03-22",7000d);
        User user3 = new User("3","zhaolei","114","1991-12-02",6000d);
        User user4 = new User("4","chong","142","1993-06-11",5500d);
        User user5 = new User("5","zhu","1167","1992-07-12",4000d);
        User user6 = new User("6","yuan","2312","1994-11-09",5000d);
        //添加到list中
        list.add(user1);
        list.add(user2);
        list.add(user3);
        list.add(user4);
        list.add(user5);
        list.add(user6);
        //获得全局性对象，连接下上文
        ServletContext servletContext = this.getServletContext();
        servletContext.setAttribute("list",list);
    }
    //获取用户数据
    private void getData(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        ServletContext context = this.getServletContext();
        //强转为User类型
        List<User> list = (List<User>)context.getAttribute("list");
        //转为json类型
        String s = JSON.toJSONString(list);
        //设置响应类型   有Json类型的都要设置
        resp.setContentType("application/json");
        //在前端输出
        PrintWriter pw =resp.getWriter();
        pw.println(s);
        pw.flush();
        pw.close();

    }
}
